<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\LoginException;
use App\Models\Apiuser;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Renting;

class ApiuserController extends Controller
{
    private $gender = ["未知","男","女"];
    public function login(Request $request){
        # 获取小程序传入的code值
        $code = $request->get("code");
        # 获取wx的openid,请求小程序的接口
        $url = sprintf(config("wx.wxlogin"),$code);
        // dump($url);
        # 发起get请求
        // echo 11;die;
        $client = new Client(["timeout" => 5,"verify" => false]);
        # 进行get请求
        $res = $client->get($url);
        $body = (string)$res->getBody();
        $arr = json_decode($body,true);
        # 得到小程序登录的唯一凭证 openid
        $openid = $arr["openid"];
        # 判断租客表中查询此数据openid是否存在，如果存在不进行任何修改或删除
        $res = Renting::where("openid",$openid)->first();
        if(!$res){
            $data["openid"] = $openid;
            $res = Renting::create($data);
        }
        // return ["status" => 0,"data" =>$arr["openid"],"msg"=>"登录成功"];
        // echo $res->openid;die;
        return ["status" => 0,"data" =>["openid" => $res->openid,"id"=>$res->id],"msg"=>"登录成功"];
    }
    # 用户授权
    public function auth(Request $request){
        # 获取到当前用户id
        $id = $request->get("id");
        # 获取传入进来的数据
        $data = [
            "nickname" => $request->get("nickname"),
            "sex" => $this->gender[$request->get("sex")],
            "avatar" => $request->get("avatar"),
        ];
        Renting::where("id",$id)->update($data);
        return ["status" => 0,"msg" => "成功","data" => ""];
    }
    # 租客信息
    public function update(Request $request){

    }
}
